package pers.vic.sso.common.util;

import pers.vic.sso.common.constant.SsoConstant;
import pers.vic.sso.common.model.RpcAccessToken;
import pers.vic.sso.common.model.SessionAccessToken;

import javax.servlet.http.HttpServletRequest;

/**
 * 描述:
 *      Session工具类
 * @author Vic.xu
 * @date 2021-11-03 11:39
 */
public class SsoSessionUtil {

    /**
     * 从session或获取 SessionAccessToken
     * @param request
     * @return
     */
    public static SessionAccessToken getAccessToken(HttpServletRequest request) {
        return (SessionAccessToken) request.getSession().getAttribute(SsoConstant.SESSION_ACCESS_TOKEN);
    }

    /**
     * SessionAccessToken存入session
     * @param request
     * @param rpcAccessToken
     */
    public static void setAccessToken(HttpServletRequest request, RpcAccessToken rpcAccessToken) {
        SessionAccessToken sessionAccessToken = null;
        if (rpcAccessToken != null) {
            sessionAccessToken = createSessionAccessToken(rpcAccessToken);
        }
        request.getSession().setAttribute(SsoConstant.SESSION_ACCESS_TOKEN, sessionAccessToken);
    }

    /**
     * 根据RpcAccessToken  创建 SessionAccessToken
     * @param accessToken
     * @return
     */
    private static SessionAccessToken createSessionAccessToken(RpcAccessToken accessToken) {
        long expirationTime = System.currentTimeMillis() + accessToken.getExpiresIn() * 1000;
        return new SessionAccessToken(accessToken.getAccessToken(), accessToken.getExpiresIn(),
                accessToken.getRefreshToken(), accessToken.getUser(), expirationTime);
    }
}
